<template>
	<cu-custom :isBack="true">
		<template #title>打卡</template>
	</cu-custom>
	
	
	<!-- <view class="page-content">
		<view style="word-break: break-all;">{{local}}</view>
		<view class="cu-btn" @click="handleClockin">打卡</view>
	</view> -->
	<view class="avatar-box theme-shadow mb-3">
		<view class="user-avatar">
			<text class="cuIcon-people" style="font-size: 130rpx;"></text>
		</view>
		<view class="name-box">
			<view class="name text-black text-ellipsis-1">{{ userInfo.username }}</view>
			<view class="phone text-gray">{{ userInfo.phone }}</view>
		</view>
		
		<view class="date text-black">{{ currDate }}</view>
	</view>
	
	<view class="clockin-box theme-shadow" v-if="todaySignIn === '0'">
		<view class="clockin-btn" :class="clockable ? '' : 'clockdisable'" @click="handleClockin">
			<view class="text-white title">打卡</view>
			<view class="text-white time">{{ currTime }}</view>
		</view>
		<view class="clockin-hint">
			<text class="cuIcon-locationfill text-gray mr-1" style="font-size:42rpx"></text>
			<text class="small-text text-gray">{{ hintText }}</text>
		</view>
	</view>
	<view class="clockin-box" v-else>
		<view class="hint-text">今日已打卡</view>
	</view>
	<view style="position: fixed; bottom: 44rpx; width: 90%; margin: 0 5%;">
		<CuButton @click="checkMap">查看地图</CuButton>
	</view>
	
	<Dialog
		:show="topHintShow"
		type="info"
		:message="topHintText"
		@confirm="topHintShow = false"
	/>
		
</template>

<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app"
import { getSchoolLocation, clockin } from "@/api/mission.js"
import { type Ref, ref, reactive, onMounted, onUnmounted } from "vue"
import CuButton from "@/components/CuButton.vue"
import { CoolWPDistance } from "@/utils/base"
import { getTicket, globalLocale, cancelGlobalLocale } from "@/utils/common"
import store from "@/store/index.js"
import Dialog from "@/components/Dialog.vue"

// #ifdef H5
import dd from "gdt-jsapi"
import { authReady } from "@/utils/JSAPI_init"
// #endif


interface IPosition {
	latitude: number
	longitude: number
	name?: string
	address?: string
}

const props = defineProps({
	mission_id: {
		type: String,
		default: null
	},
	todaySignIn: {
		type: String,
		default: "0"
	}
})
const todaySignIn: Ref<string> = ref("0")
const clockFinishedText: Ref<string> = ref("今日已打卡")
let schoolLocaltion:IPosition = {
	latitude: 0,
	longitude: 0
}
const userInfo = reactive({
	"avatar": "/static/images/demoicon.jpg",
	"username": "",
	"phone": "",
	"role": 1,
	"school": "",
	"position": ""
})
const currDate: Ref<string> = ref("")
const hintText: Ref<string> = ref("您当前不在打卡范围内")
const currTime: Ref<string> = ref("00 : 00 : 00")
const clockable: Ref<boolean> = ref(false)
const topHintShow = ref(false)
const topHintText: Ref<string> = ref("")
const currentPosition:IPosition = reactive({
	latitude: 0,
	longitude: 0
})

let timeInterval = null
let locationInterval = null

const clockinable = () => {
	clockable.value = true
	// hintText.value = "您已到达打卡范围内"
}
const checkMap = () => {
	
	// #ifdef MP-ALIPAY
	uni.openLocation({
		latitude: schoolLocaltion.latitude,
		longitude: schoolLocaltion.longitude,
		name: schoolLocaltion.name,
		address: schoolLocaltion.address,
		complete(res) {
			console.log("打开地图回调", res)
		}
	})
	// #endif
	
	// #ifdef H5
	dd.showOnMap({
		latitude: schoolLocaltion.latitude,
		longitude: schoolLocaltion.longitude,
		title: schoolLocaltion.name,
	}).then(res => {
		console.log(res)
		uni.showToast({
			icon: "none",
			title: JSON.stringify(res)
		})
	}).catch(err => {
		console.log(err)
		uni.showToast({
			icon: "none",
			title: JSON.stringify(err)
		})
	})
	// #endif
}
const handleClockin = ():void => {
	if (!clockable.value) {
		uni.showToast({
			icon: "none",
			title: "您未在打卡范围内"
		})
		return
	}
	uni.showLoading({
		title: "加载中",
		mask: true
	})
	clockin(props.mission_id)
		.then((res: any) => {
			uni.hideLoading()
			todaySignIn.value = "1"
			clockFinishedText.value = "打卡成功" + new Date().format("MM月dd日hh:mm")
		})
		.catch((err: any) => {
			console.log(err)
			if (err.msg.indexOf("已打卡") > -1) {
				clockFinishedText.value = "今日已打卡"
				todaySignIn.value = "1"
			}
		})
	
}

const updateCurrLocation = ():void => {
	// #ifdef MP-ALIPAY
	uni.getLocation({
		success: function(res:IPosition) {
			currentPosition.latitude = Number(res.latitude)
			currentPosition.longitude = Number(res.longitude)
			
			const distance = CoolWPDistance(currentPosition.longitude, currentPosition.latitude, schoolLocaltion.longitude, schoolLocaltion.latitude)
			console.log(currentPosition.longitude, currentPosition.latitude, schoolLocaltion.longitude, schoolLocaltion.latitude)
			console.log("distance", distance)
			if (distance < 5000) {
				clockinable()
			}
		},
		fail: function(err) {
			uni.showToast({
				icon: "none",
				title: "无法获取到当前坐标"
			})
			console.log("无法获取到当前坐标", err)
		}
	})
	// #endif
	
	// #ifdef H5
	// 停掉外面的
	
	authReady(() => {
		dd.getGeolocation({
		    coordinate : 1,
		    withReGeocode : false,
		    useCache: true ,
		}).then(() => {
		}).catch((err) => {
			// uni.showToast({
			// 	icon: "none",
			// 	title: "失败调用" + JSON.stringify(err)
			// })
			if (err.errorCode === "4" || err.errorCode === "11") {
				topHintShow.value = true
				topHintText.value = "请确认定位相关权限已开启"
			} else if (err.errorCode === "12") {
				uni.showToast({
					icon: "none",
					title: "网络异常，请稍后再试"
				})
			} else if (err.errorCode === "13") {
				uni.showToast({
					icon: "none",
					title: "定位失败，请稍后再试"
				})
			} else if (err.errorCode === "14") {
				uni.showToast({
					icon: "none",
					title: "业务定位超时，请退出重试"
				})
			}
		})
		
		dd.startGeolocation({
			"targetAccuracy": 200,
			"useCache": false,
			"callBackInterval": 6000,
			"sceneId": "clock",
			"withReGeocode": true,
			"onSuccess": (res) => {
				if (!res.address) return
				hintText.value = res.address
				if (CoolWPDistance(Number(schoolLocaltion.longitude), Number(schoolLocaltion.latitude), Number(res.longitude), Number(res.latitude)) < 1000) {
					clockinable()
				}
			}
		})
	})
	// #endif
}



onLoad((options) => {
	todaySignIn.value = options.todaySignIn
	// #ifdef MP-ALIPAY
	locationInterval = setInterval(() => {
		updateCurrLocation()
	}, 5000)
	// #endif
	const { avatar, role, username, phone, school, position } = store.getters.userInfo
	userInfo.avatar = avatar
	userInfo.role = role
	userInfo.username = username
	userInfo.phone = phone
	userInfo.school = school
	userInfo.position = position
	
	
	dd.stopGeolocation({ sceneId: "global" })
		.then((res) => {
			
		})
	getSchoolLocation(options.mission_id)
		.then((res:any):void => {
			schoolLocaltion.longitude = Number(res.longitude)
			schoolLocaltion.latitude = Number(res.latitude)
			schoolLocaltion.name = res.schoolName
			schoolLocaltion.address = res.address
			updateCurrLocation()
		})
		.catch((err) => {
			uni.showToast({
				icon: "none",
				title: "无法获取到学校位置"
			})
		})
		
	currDate.value = new Date().format("M月dd日")
	currTime.value = new Date().format("hh : mm : ss")
	timeInterval = setInterval(() => {
		currTime.value = new Date().format("hh : mm : ss")
	}, 1000)
	
	
})
onUnmounted(() => {
	clearInterval(timeInterval)
	clearInterval(locationInterval)
	// #ifdef H5
	globalLocale()
	dd.stopGeolocation({ sceneId: "clock" })
		.then((res) => {
			
		})
	
	// #endif
})
</script>

<style lang="stylus" scoped>
.avatar-box	
	height: 250rpx
	background #fff
	display: flex
	padding 60rpx 40rpx
	align-items: center
	.user-avatar
		width: 130rpx
		height: 130rpx
		margin-right: 12rpx
		border-radius: 65rpx
		overflow: hidden
		background-color #eee
		image
			height: 100%
			width: 100%
	.name-box
		width: 360rpx
		.name
			font-size 44rpx
			line-height 60rpx
			padding-bottom 12rpx
		.phone
			font-size 30rpx
.clockin-box
	background-color #fff
	min-height 546rpx
	padding 100rpx 0
	.hint-text
		padding 0 50rpx
		font-weight: bold
		font-size: 44rpx
		text-align: center
	.clockin-btn
		margin: 0 auto 30rpx;
		height: 270rpx
		width: 270rpx
		border-radius: 135rpx
		background: linear-gradient(#54CBFD, #2791FD);
		box-shadow: 0px 0px 20rpx rgba(30, 75, 147, 0.5)
		display: flex
		flex-wrap: wrap
		align-items: center
		.title
			font-weight: 500
			width: 100%
			text-align: center
			font-size: 48rpx
			padding-top 60rpx
		.time
			width: 100%
			text-align: center
			padding-bottom 60rpx
	.clockin-hint
		display: flex
		align-items: center
		justify-content: center
		padding: 0 80rpx
	.clockdisable
		background: linear-gradient(#adadad, #767676);
		box-shadow: 0px 0px 20rpx rgba(0, 0, 0, 0.5)
		
</style>